package org.arch_learn.io.netty_demo.chatroom;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {
    public static List<Channel> channelList = new ArrayList<>();

    /**
     * 通道就绪事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //当有新的客户端连接的时候，将通道放入集合
        Channel channel = ctx.channel();
        channelList.add(channel);
        System.out.println("[Server]:" +
                channel.remoteAddress()
                        .toString().substring(1) + "在线。");
    }

    /**
     * 处理通道未就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("[Server]:" +
                channel.remoteAddress()
                        .toString().substring(1) + "下线。");
        channelList.remove(channel);
    }

    /**
     * 通道读取事件
     *
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //当前发送消息的通道，当前发送的客户端连接
        Channel channel = channelHandlerContext.channel();
        channelList.stream()
                .filter(c -> c != channel)
                .forEach(c -> {
                    c.writeAndFlush("[" + channel.remoteAddress()
                            .toString().substring(1) + "]:" + s);
                });

    }

    /**
     * 处理异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        channelList.remove(channel);
        System.out.println("[Server]:" +
                channel.remoteAddress()
                        .toString().substring(1) + "发生异常。");
    }
}
